package com.example.echoewish.ui.main_activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.example.echoewish.R;
import com.example.echoewish.ui.EchoWishCompatActivity;
import com.example.echoewish.ui.home_activity.PostDetailViewModel;

public class SearchContentActivity extends EchoWishCompatActivity {

    private EditText queryEditText;
    private Button cancelSearchButton;
    private FrameLayout frameLayout;
    private SearchContentViewModel searchContentViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        searchContentViewModel.getHotSearch();
    }

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_search_content);
    }

    @Override
    public void initView() {
        queryEditText=findViewById(R.id.query);
        cancelSearchButton=findViewById(R.id.cancel_search_button);
        frameLayout=findViewById(R.id.home_search_content_frameLayout);

        cancelSearchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        queryEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH)
                {
                    getSupportFragmentManager().beginTransaction().replace(R.id.home_search_content_frameLayout,SearchAnswerFragment.newInstance()).commit();
                    searchContentViewModel.keyWordMutableLiveData.postValue(queryEditText.getText().toString());
                }
                return false;
            }
        });
        getSupportFragmentManager().beginTransaction().replace(R.id.home_search_content_frameLayout,HotSearchRankingFragment.newInstance()).commit();

    }

    @Override
    public void initViewModel() {
        searchContentViewModel=new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(SearchContentViewModel.class);
    }

    @Override
    public void observeLiveData() {
        searchContentViewModel.keyWordMutableLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                searchContentViewModel.getPartPostMessageByKeyWord();
            }
        });
    }
}